/*
 * @Description: 渲染进程-拖动
 * @Date: 2024-09-30 15:24:03
 * @FilePath: \demod:\12electron\b站向军课程\electron-camera\src\renderer\src\composables\useDrag.ts
 */
class Drag {
  private pageX = 0
  private pageY = 0
  private body?: HTMLBodyElement
  constructor() { }

  private mouseDown = (e: MouseEvent) => {
    // 初始点击记录起始位置
    this.pageX = e.pageX
    this.pageY = e.pageY
    const mouseMoveCallback = this.mouseMove // 回调函数为自定义的mouseMove函数

    // 鼠标拖拽的时候，添加回调函数
    this.body?.addEventListener('mousemove', mouseMoveCallback)
    // 鼠标抬起的时候移除事件
    this.body?.addEventListener('mouseup', () => {
      this.body?.removeEventListener('mousemove', mouseMoveCallback)
    })
    // 鼠标移出的时候移除事件
    this.body?.addEventListener('mouseout', () => {
      this.body?.removeEventListener('mousemove', mouseMoveCallback)
    })
  }

  // 自定义的鼠标移动函数
  private mouseMove = (e: MouseEvent) => {
    // 计算移动距离
    const moveX = e.pageX - this.pageX
    const moveY = e.pageY - this.pageY
    window.api.drag({ x: moveX, y: moveY }) // dom->预加载脚本->主进程
  }

  public run = () => {
    window.addEventListener('DOMContentLoaded', () => {
      this.body = document.querySelector('body')!

      this.body.addEventListener('mousedown', this.mouseDown)
    })
  }
}

export default () => {
  const drag = new Drag()
  return { drag }
}
